<template>
  <div id="student">
    <el-row class="padding-50">
      <el-col :span="24">
        <ul class="list">
          <li class="logo">
            <i class="iconfont icon-kaoshi"></i>
            <span>DORO-Learning-Online</span>
          </li>
          <li class="logo">章节学习</li>
          <li><router-link :to="`/student/learn_document/${courseId}`">课程资料</router-link></li>
          <li><router-link :to="`/student/learn_info/${courseId}`">课程信息</router-link></li>
          <li><router-link :to="`/student/AIhelper/${courseId}`">智能学习助手</router-link></li>
          <li><router-link to="/student/message">我的消息</router-link></li>
          <li><router-link to="/student">返回首页</router-link></li>
          <li class="right" @mouseenter="flag = true" @mouseleave="flag = false">
            <a href="javascript:;">
              <i class="iconfont icon-Userselect icon"></i>{{ user.userName }}
            </a>
            <div class="msg" v-if="flag">
              <p @click="manage">管理中心</p>
              <p class="exit" @click="exit">退出</p>
            </div>
          </li>
        </ul>
      </el-col>
    </el-row>
    <div class="divide"></div>
    <div class="progress-container">
      <h3 class="progress-title">学习进度</h3>
      <el-progress :percentage="progressPercentage" :stroke-width="15" text-inside></el-progress>
    </div>

    <div class="main">
      <div v-if="chapters.length > 0">
        <ul class="chapter-list">
          <ChapterItem
            v-for="chapter in chapters"
            :key="chapter.id"
            :chapter="chapter"
            @view-file="handleViewFile"
            @click-chapter="handleClickChapter"
          />
        </ul>
      </div>
      <div v-else>
        <p>暂无章节内容或正在加载中...</p>
      </div>
    </div>

    <router-view></router-view>
    <v-footer></v-footer>
  </div>
</template>

<script>
import myFooter from '@/components/student/myFooter'
import ChapterItem from '@/components/student/ChapterItem.vue'
import { mapState } from 'vuex'

export default {
  name: 'Learn',
  components: {
    'v-footer': myFooter,
    ChapterItem
  },
  data() {
    return {
      flag: false,
      user: {},
      courseId: null,
      studentId: null, // <-- Added studentId to data
      chapters: [],
      // Backend will provide these counts for accurate progress
      totalChaptersCount: 0,
      learnedChaptersCount: 0,
      progressPercentage: 0,
      // Frontend set to track clicked chapters to avoid redundant API calls
      // if a chapter is clicked multiple times before a full refresh
      recordedChapterIds: new Set(),
    }
  },
  created() {
    this.userInfo()
    this.courseId = this.$route.params.courseId
    if (this.courseId) {
      this.loadChaptersAndProgress() // <-- Combined loading logic
    }
  },
  methods: {
    userInfo() {
      const name = this.$cookies.get('cname')
      const id = this.$cookies.get('cid')
      this.user = { userName: name, studentId: id }
      this.studentId = id // Set studentId from cookies
    },
    exit() {
      this.$cookies.remove('cname')
      this.$cookies.remove('cid')
      this.$router.push('/')
    },
    manage() {
      this.$router.push('/student/manager')
    },
    async loadChaptersAndProgress() {
      try {
        // 1. Load Chapters (for display)
        const chapterRes = await this.$axios.get('/api/chapter/courseid', {
          params: { courseID: this.courseId }
        });
        if (chapterRes.data.code === 200 && chapterRes.data.data) {
          this.chapters = this.processChaptersWithFakeFiles(chapterRes.data.data);
          console.log("Chapters loaded for display:", this.chapters);
        } else {
          this.$message.error('章节加载失败: ' + (chapterRes.data.msg || '未知错误'));
          this.chapters = [];
        }

        // 2. Load Student Progress (for the progress bar)
        await this.fetchStudentProgress();

      } catch (error) {
        this.$message.error('加载课程信息或进度失败，请检查网络或服务器: ' + (error.message || '未知错误'));
        this.chapters = [];
        this.totalChaptersCount = 0;
        this.learnedChaptersCount = 0;
        this.updateProgressPercentage();
      }
    },
    // Fetches and updates progress from the backend
    async fetchStudentProgress() {
      if (!this.courseId || !this.studentId) return;

      try {
        const progressRes = await this.$axios.get('/api/chapter/studentprogress', {
          params: { courseID: this.courseId, studentID: this.studentId }
        });

        if (progressRes.data.code === 200 && progressRes.data.data) {
          const { learnedCount, totalCount } = progressRes.data.data;
          this.learnedChaptersCount = learnedCount;
          this.totalChaptersCount = totalCount;
          this.updateProgressPercentage();
          console.log(`Student Progress: Learned ${learnedCount} of ${totalCount} chapters.`);
          
          // Optionally, if the backend returns a list of learned chapter IDs,
          // you could populate recordedChapterIds here.
          // For now, we just rely on learnedCount/totalCount.
          // This Set primarily prevents re-sending click requests immediately.

        } else {
          this.$message.warning('无法获取学生学习进度: ' + (progressRes.data.msg || '未知错误'));
          this.learnedChaptersCount = 0;
          this.totalChaptersCount = 0;
          this.updateProgressPercentage();
        }
      } catch (error) {
        console.error('Error fetching student progress:', error);
        this.$message.error('获取学习进度失败: ' + (error.message || '未知错误'));
        this.learnedChaptersCount = 0;
        this.totalChaptersCount = 0;
        this.updateProgressPercentage();
      }
    },
    // Processes chapters to add fake files for display purposes
    processChaptersWithFakeFiles(chapterList) {
      let fileIdCounter = 1;
      const append = (chapter) => {
        if (!Array.isArray(chapter.files)) {
            chapter.files = [];
        }
        chapter.files.push(
          { name: `[示例文件] ${chapter.title}-A`, fakeId: fileIdCounter++, chapterId: chapter.id },
          { name: `[示例文件] ${chapter.title}-B`, fakeId: fileIdCounter++, chapterId: chapter.id }
        );
        if (Array.isArray(chapter.children)) {
          chapter.children = chapter.children.map(append);
        } else {
          chapter.children = [];
        }
        return chapter;
      };
      return chapterList.map(append);
    },
    // Updates the frontend progress percentage based on backend data
    updateProgressPercentage() {
      if (this.totalChaptersCount > 0) {
        // Ensure progress is always between 0 and 100, and is an integer
        this.progressPercentage = Math.min(100, Math.floor((this.learnedChaptersCount / this.totalChaptersCount) * 100));
      } else {
        this.progressPercentage = 0;
      }
      console.log(`Calculated Progress: ${this.progressPercentage}%`);
    },
    
    // This method is called when a file is clicked.
    // NOTE: The backend APIs provided (`/chapter/record`, `/chapter/studentprogress`)
    // appear to only track 'chapters'. So, clicking a file will not affect
    // the main progress bar which is based on chapter completion.
    // It will still show a local success message.
    handleViewFile(file) {
      this.$message.success(`查看 [${file.name}] 成功，但文件观看不计入章节进度。`);
      // You could add client-side tracking for files here if needed,
      // but it won't affect the backend-driven progress bar.
    },

    // This method is called when a chapter title is clicked.
    // It sends a request to the backend to record the chapter as learned.
    async handleClickChapter(chapterId) {
      if (!this.studentId || !chapterId) {
        this.$message.error('无法记录章节学习：学生ID或章节ID缺失。');
        return;
      }

      // Prevent redundant API calls if already recorded recently (client-side check)
      const chapterIdentifier = `chapter-${chapterId}`;
      if (this.recordedChapterIds.has(chapterIdentifier)) {
        console.log(`Chapter ${chapterId} already recorded (client-side).`);
        this.$message.info('您已点击过此章节。');
        return;
      }

      try {
        const recordRes = await this.$axios.post('/api/chapter/record', {
          studentID: this.studentId,
          chapterID: chapterId
        });

        if (recordRes.data.code === 200) {
          this.$message.success(`章节 "${chapterId}" 学习进度已记录！`);
          this.recordedChapterIds.add(chapterIdentifier); // Mark as recorded client-side
          await this.fetchStudentProgress(); // Fetch updated progress from backend
        } else {
          this.$message.error('记录章节学习失败: ' + (recordRes.data.msg || '未知错误'));
        }
      } catch (error) {
        this.$message.error('记录章节学习请求失败，请检查网络或服务器: ' + (error.message || '未知错误'));
        console.error('Error recording chapter progress:', error);
      }
    }
  },
  computed: mapState(['isPractice'])
}
</script>

<style scoped>
.divide{
  padding: 20px 50px;
  background-color: #f0f2f5;
  border-bottom: 1px solid #ebeef5;
  text-align: center; /* Center the title and progress bar */
}
.progress-container {
  padding: 20px 50px;
  background-color: #f0f2f5;
  border-bottom: 1px solid #ebeef5;
  text-align: center; /* Center the title and progress bar */
}

.progress-title {
  margin-bottom: 10px;
  font-size: 1.1em;
  color: #555;
}
.right .icon {
  margin-right: 6px;
}
#student .padding-50 {
  margin: 0 auto;
  padding: 0 50px;
  box-shadow: 0 0 10px 4px rgba(1, 149, 255, 0.1);
  background-color: #fff;
}
.list a {
  text-decoration: none;
  color: #334046;
}
li {
  list-style: none;
  line-height: 60px;
}
#student .list {
  display: flex;
}
#student .list li {
  padding: 0 20px;
  cursor: pointer;
}
#student .list li:hover {
  background-color: #0195ff;
  transition: all 0.3s ease;
}
#student .list li:hover a {
  color: #fff;
}
#student .list .right {
  margin-left: auto;
  position: relative;
}
#student .list li.right:hover a {
  color: #000;
}
#student .list .logo {
  display: flex;
  font-weight: bold;
  color: #2f6c9f;
}
#student .list .logo i {
  font-size: 50px;
}
.right .msg {
  text-align: center;
  position: absolute;
  top: 60px;
  left: 0;
  display: flex;
  flex-direction: column;
  border-radius: 2px;
  border-bottom: 3px solid #0195ff;
  background-color: #fff;
}
.right .msg p {
  height: 40px;
  line-height: 40px;
  width: 105px;
}
.right .msg p:hover {
  background-color: #0195ff;
}
.main {
  padding: 20px 50px;
}
.chapter-item {
  margin: 10px auto;
  padding-left: 0;
  list-style: none;
}

/* 每一个章节标题的大框 */
.chapter-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 20px;
  background-color: #f5f7fa;
  border: 1px solid #dcdfe6;
  border-radius: 8px;
  margin-bottom: 6px;
  cursor: pointer;
  font-weight: 600;
  transition: background-color 0.3s;
  width: calc(100% - 40px); /* 保持屏幕宽度一致 */
}

.chapter-title:hover {
  background-color: #e0f0ff;
}

/* 子列表缩进，层级越深缩进越多 */
.child-list {
  margin-top: 8px;
  margin-left: 40px; /* 控制子章节缩进 */
  padding-left: 0;
}

/* 文件样式 */
.file {
  background-color: #ffffff;
  border-left: 3px solid #409eff;
  padding: 8px 16px;
  margin: 6px 0;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: background 0.2s;
}

.file:hover {
  background-color: #f0faff;
  color: #409eff;
}
</style>
